package 其他.叠积木;

import java.util.Arrays;
import java.util.Scanner;

public class Solution_回溯 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        String[] strings = s.split(" ");
        int[] ints = new int[strings.length];
        // 数组填充
        for (int i = 0; i < strings.length; i++) {
            ints[i]=Integer.valueOf(strings[i]);
        }

        int result = -1;
        for (int k = 2; k < ints.length; k++) {
            boolean check = check(ints, k);
            if (check) {
                result = Math.max(result, k);
            }
        }

        System.out.println("最大为:" + result + "层");

    }

    public static boolean check(int[] nums, int k) {
        Arrays.sort(nums);
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        //特判1
        if (sum % k != 0) {
            return false;
        }
        //特判2
        if (k == 1) {
            return true;
        }
        //特判3
        if (nums[nums.length - 1] > sum / k) {
            return false;
        }
        int[] buckets = new int[k];
        Arrays.fill(buckets, sum / k);
        return dfs(buckets, k, nums.length - 1, nums);
    }


    public static boolean dfs(int[] buckets, int k, int cur, int[] nums) {
        //1.边界条件: 说明把数组里的数字全部放进了桶里面
        if (cur == -1) {
            return true;
        }

        //2.横向遍历桶: 并且剪枝
        for (int i = 0; (i < k); i++) {
            if ((i>1)&&(buckets[i] == buckets[i - 1])){
                continue;
            }
            if (buckets[i] >= nums[cur]) {
                buckets[i] -= nums[cur];
                //3.纵向遍历数组
                if (dfs(buckets, k, cur - 1, nums)) {
                    return true;
                }
                //4.回溯
                buckets[i] += nums[cur];
            }
        }
        //3.该元素把所有的桶都尝试了一遍,无法放下, 则失败
        return false;
    }
}
